<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\controller;

use app\common\controller\ControllerBase;
use think\facade\Session;

/**
 * 登录控制器
 */
class Login extends ControllerBase
{
    
    /**
     * 登录
     */
    public function login()
    {
        
        is_login() && $this->jump(RESULT_REDIRECT, '已登录则跳过登录页', url('index/index'));
        
        // 关闭布局
        \think\facade\View::engine()->layout(false);
        
        return $this->fetch('login');
    }
    
    /**
     * 登录处理
     */
    public function loginHandle()
    {
        
        $username = $this->param['username'] ?? '';
        $password = $this->param['password'] ?? '';
        $verify   = $this->param['verify']   ?? '';
        
        $this->jump($this->logicLogin->loginHandle($username, $password, $verify));
    }
    
    /**
     * 注销登录
     */
    public function logout()
    {
        
        $this->jump($this->logicLogin->logout());
    }
    
    /**
     * 清理缓存
     */
    public function clearCache()
    {
        
        $this->jump($this->logicLogin->clearCache());
    }
    
    /**
     * 调试：验证码实时校验（不消耗验证码）
     */
    public function captchaDebugVerify()
    {
        $code = $this->param['code'] ?? '';
        $has  = \think\facade\Session::has('captcha');
        $key  = $has ? \think\facade\Session::get('captcha.key') : null;

        $ok = false;
        if (!empty($key) && $code !== '') {
            $ok = password_verify(mb_strtolower($code, 'UTF-8'), $key);
        }

        return json([
            'ok'          => $ok,
            'hasCaptcha'  => $has,
            // 改为框架会话ID，避免原生 session_id() 为空
            'sid'         => \think\facade\Session::getId(),
            'code'        => $code,
        ]);
    }
    
}
